using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using System;
using UnityEditor;
namespace BehTree{
public enum NodeKind{
    Root,
    Brancher,
    Leave,
    Jump
}
public enum BrancherKind{
    Selector
}
public class NodeBase : MonoBehaviour
{   
    public Driver driver;
    bool lastDefault;
    public static NodeBase defaultNode;
    public int id = 0;
    public NodeKind nodeKind = NodeKind.Brancher;
    public bool active = true;             //是否开启
    public bool isDefault;          //是否是默认行为
    public bool jumpToDefault;      //NodeKind.Jump: 是否跳转到默认节点
    public NodeBase targetNode;     //NodeKind.Jump: 跳转目标
    public virtual void Enter() { }
    public virtual void Exit() { }
    [SerializeField]
    public UnityEvent behaviourEvents;  //!NodeKind.Jump：  节点行为事件
    [SerializeField]
    public CondEvent condition;
    [SerializeField]
    public CondEvent exitCondition;
    [SerializeField]
    public float enterDelay;        //开始时延时
    public float endDelay;          //结束时延时
    // public AnimationClip animationWith; //伴随动画（可选）
    public BrancherKind brancherKind;   //NodeKind.Brancher: 分支结点类型（决定子节点优先级规则）
    public bool randExcute;         //BrancherKind.Selector: 是否随机调用
    public bool DetectCondition()
    {
        if(condition==null||condition.Count==0)
        {
            Debug.LogError("未设置跳转条件！");
            return false;
        }
        return condition.Invoke();
    }
    public bool DetectExitCondition()
    {
        if(nodeKind!=NodeKind.Leave)
        {
            Debug.LogWarning("非叶子节点判断退出条件！");
            return false;
        }
        if(exitCondition==null||exitCondition.Count==0)
        {
            Debug.LogError("未设置跳转条件！");
            return false;
        }
        return exitCondition.Invoke();
    }
    public void Exceute()
    {
        if (nodeKind == NodeKind.Jump)
            return;
        behaviourEvents.Invoke();
    }
    #if UNITY_EDITOR
    [CustomEditor(typeof(NodeBase))]
    public class NodeBase_Inspector : Editor
    {
        NodeBase script;
        private SerializedProperty events;
        SerializedProperty cond;
        SerializedProperty exitCond;

        public void OnEnable()
        {
            script = target as NodeBase;
            events = serializedObject.FindProperty("behaviourEvents");
            cond = serializedObject.FindProperty("condition");
            exitCond = serializedObject.FindProperty("exitCondition");
        }
        public override void OnInspectorGUI()
        {
            serializedObject.Update();
            //Essential Setting
            script.nodeKind = (NodeKind)EditorGUILayout.EnumPopup("节点类型",script.nodeKind);
            if(script.nodeKind==NodeKind.Root)
            {
                script.active = true;
            }
            else if(script.isDefault&&script.nodeKind != NodeKind.Jump)
            {
                script.active = true;
            }
            else
                script.active = EditorGUILayout.Toggle("启用", script.active);
            if (!script.active)
                return;

            //Default Setting And Show====================================================================//
            GUI.enabled = false;
            if (script.nodeKind == NodeKind.Jump || script.nodeKind == NodeKind.Leave)
            {
                EditorGUILayout.ObjectField(defaultNode != null?"默认节点":"未设置默认节点", defaultNode, typeof(NodeBase), true);
            }
            GUI.enabled = true;
            if (script.nodeKind != NodeKind.Jump)
            {
                if (script.nodeKind != NodeKind.Leave)
                {
                    if (defaultNode == null && !script.isDefault)
                    {
                        script.lastDefault = script.isDefault;
                        script.isDefault = EditorGUILayout.Toggle("设为默认行为（当前未设置）", script.isDefault);
                        if(script.isDefault)
                            defaultNode = script;
                    }
                    else if(defaultNode!=null&&script.isDefault)
                    {
                        if(defaultNode!=script)
                        {
                            script.isDefault=false;
                        }
                        else
                        {
                            script.lastDefault = script.isDefault;
                            script.isDefault = EditorGUILayout.Toggle("【当前行为默认】", script.isDefault);
                            if(!script.isDefault)
                                defaultNode = null;
                        }
                    }
                    else if (defaultNode == null&&script.isDefault)
                    {
                        Debug.LogWarning("默认节点检测出错！请尝试重设默认节点！");
                        defaultNode = script;
                    }
                    else if(defaultNode!=null&&!script.isDefault)
                    {
                        GUI.enabled = false;
                        EditorGUILayout.ObjectField("默认节点",defaultNode,typeof(NodeBase),true);
                        GUI.enabled = true;
                    }
                }
                // script.animationWith = EditorGUILayout.ObjectField("行为动画", script.animationWith, typeof(AnimationClip), true) as AnimationClip;
                // if (script.animationWith != null)
                // {
                //     script.enterDelay = EditorGUILayout.FloatField("开始延时", script.enterDelay);
                //     script.endDelay = EditorGUILayout.FloatField("结束延时",script.endDelay);
                // }
            }
            else
            {
                script.jumpToDefault = EditorGUILayout.Toggle("是否跳转到默认行为",script.jumpToDefault);
                if(!script.jumpToDefault)
                script.targetNode = EditorGUILayout.ObjectField("目标节点",script.targetNode,typeof(NodeBase),true) as NodeBase;
            }

            //BrancherKind Setting============================================================================//
            if(script.nodeKind==NodeKind.Root||script.nodeKind==NodeKind.Brancher)
            {
                script.brancherKind = (BrancherKind)EditorGUILayout.EnumPopup("分支点类型",script.brancherKind);
                if(script.brancherKind == BrancherKind.Selector)
                {
                    if(script.transform.childCount>1)
                    {
                        script.randExcute = EditorGUILayout.Toggle("是否随机跳转",script.randExcute);
                    }
                }
            }

            //Condition Setting===========================================================================//
            if (script.nodeKind != NodeKind.Root)
            {
                EditorGUILayout.PropertyField(cond, new GUIContent("跳转条件"));
            }
            if (script.nodeKind == NodeKind.Leave)
            {
                EditorGUILayout.PropertyField(exitCond, new GUIContent("结束条件"));
            }
            if (script.nodeKind != NodeKind.Jump)
            {
                EditorGUILayout.PropertyField(events, new GUIContent("行为函数"));
            }

            //Debug Info===================================================================================//
            switch (script.nodeKind)
            {
                case NodeKind.Root:

                    break;
                case NodeKind.Jump:
                    if(script.transform.childCount>0)
                    {
                        Debug.LogWarning("跳转节点下的子行为将不会执行！");
                    }
                    break;
                case NodeKind.Brancher:
                    if(script.transform.childCount==0)
                    {
                        Debug.LogWarning("若分支节点无子行为，将无法跳出！");
                    }
                    break;
                case NodeKind.Leave:
                    if(script.transform.childCount>0)
                    {
                        Debug.LogWarning("叶子节点下的子行为将不会执行！");
                    }
                    break;
            }
            serializedObject.ApplyModifiedProperties();
        }

        
    }
    #endif
}
}